package com.example.dify;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import net.sf.json.JSONObject;

import com.fasterxml.jackson.databind.node.ArrayNode;

public class ChatClient {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://172.20.68.15:1880/v1/chat-messages");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer app-pHgGDWVCLRa1oqQBHiyoKlSS");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // 使用Jackson库构建JSON
        // 导入Jackson库的ObjectMapper类
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode json = mapper.createObjectNode();
        json.putObject("inputs");
        json.put("query", "你好");
        json.put("response_mode", "streaming");
        json.put("conversation_id", "");
        json.put("user", "abc-123");

        // 导入ArrayNode类，解决无法解析类型的问题
        ArrayNode files = json.putArray("files");
        ObjectNode file = files.addObject();
        file.put("type", "image");
        file.put("transfer_method", "remote_url");
        file.put("url", "https://cloud.dify.ai/logo/logo-site.png");

        String jsonInput = mapper.writeValueAsString(json);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInput.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // 处理错误响应
        if (responseCode >= 400) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), "utf-8"))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    errorResponse.append(line);
                }
                System.err.println("错误响应: " + errorResponse);
            }
            return;
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "utf-8"))) {
            String responseLine;
            StringBuilder finalAnswer = new StringBuilder();
            // 优化后的流式数据处理
            while ((responseLine = br.readLine()) != null) {
                if (responseLine.startsWith("data: {")) {
                    String jsonStr = responseLine.substring(6);
                    JSONObject node = JSONObject.fromObject(jsonStr);
                    String event = node.getString("event");
                    if ("agent_message".equals(event)) {
                        String answer = node.getString("answer");
                        finalAnswer.append(answer);
                    }
                }
            }
            System.out.println("最终答案: " + finalAnswer);
        }
    }

}
